<template>
    <div>
        <!--<h1 class="page_title">用户管理</h1>-->
        <el-button type="primary" class="add_btn" icon="el-icon-plus" size="small" @click="showCreateDialogForm">
            新增用户
        </el-button>
        <div class="search_box">
            <el-form :inline="true" :model="formSearch">
                <el-form-item label="角色">
                    <AutoSelectForm @selectCb="selectCb" key="roleId" fieldName="roleId"
                                    dataType="role"></AutoSelectForm>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="formSearch.realName" size="small"></el-input>
                </el-form-item>
                <el-form-item label="组织">
                    <AutoSelectForm @selectCb="selectCb" :defaultValue="$route.query.deptId" key="deptId"
                                    fieldName="deptId"
                                    dataType="dept"></AutoSelectForm>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="formSearch.forbidden" clearable size="small">
                        <el-option key="true" label="被禁用" value="true"></el-option>
                        <el-option key="false" label="可用" value="false"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" icon="el-icon-search" size="mini" type="primary" plain>查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table_content">
            <el-table
                    size="small"
                    border
                    ref="multipleTable"
                    :data="tableList"
                    tooltip-effect="dark"
                    v-loading="searchLoading"
                    style="width: 100%"
                    :header-cell-style="{backgroundColor:'#fafafa',fontSize:'15px',color:'#333333'}"
                    :cell-style="{fontSize:'15px'}"
            >
                <el-table-column
                        type="index"
                        label="序号"
                        align="center"
                        fixed="left"
                        width="70">
                </el-table-column>
                <el-table-column
                        prop="userName"
                        min-width="120"
                        align="center"
                        label="用户名">
                </el-table-column>
                <el-table-column
                        prop="realName"
                        min-width="120"
                        align="center"
                        label="姓名">
                </el-table-column>
                <el-table-column
                        prop="sex"
                        min-width="120"
                        align="center"
                        label="性别">
                </el-table-column>
                <el-table-column
                        prop="phone"
                        min-width="120"
                        align="center"
                        label="手机号">
                </el-table-column>
                <el-table-column
                        prop="role"
                        min-width="120"
                        align="center"
                        label="角色">
                </el-table-column>
                <el-table-column
                        prop="deptName"
                        min-width="120"
                        align="center"
                        label="组织">
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        min-width="120"
                        show-overflow-tooltip
                        align="center"
                        label="创建时间">
                </el-table-column>
                <el-table-column
                        prop="enable"
                        label="是否启用"
                        align="center"
                        min-width="100">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.forbidden" :active-value="false" :inactive-value="true"
                                   @change="changeEnable(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="220"
                        show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button @click="showUserDetail(scope.row)" size="mini">查看</el-button>
                        <el-button @click="showUpdateDialogForm(scope.row)" type="primary" size="mini">编辑</el-button>
                        <el-button @click="showDeleteDialogForm(scope.row)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination_box">
                <div class="pagination_box_content">
                    <el-pagination
                            background
                            @current-change="handleCurrentChange"
                            :current-page="formSearch.pageNum"
                            layout="total, sizes, prev, pager, next, jumper"
                            :page-size="formSearch.pageSize"
                            :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <CreateDialogForm width="40%" title="新增用户" :dialogFormVisible="createDialogFormVisible" :form="form"
                          :hideDialog="hideCreateDialogForm"
                          :submit="addUser" :columns="columns"
                          :loading="addUserLoading" :error="error"/>
        <UpdateDialogForm width="40%" title="修改用户" :dialogFormVisible="updateDialogFormVisible"
                          :hideDialog="hideUpdateDialogForm"
                          :submit="updateUser" :updateItem="updateItem" :columns="columns" :form="form"
                          :loading="updateUserLoading" :error="error"/>
        <UserDetail :detailData="detailData" :visible="userDetailShow"
                    :hideDialog="hideUserDetail"></UserDetail>
        <el-dialog
                title="提示"
                :visible.sync="deleteDialogShow"
                :close-on-click-modal="false"
                width="400px"
                center>
            <div class="icon_question">?</div>
            <span>您选择了1条数据记录是否确认删除?</span>
            <span slot="footer" class="dialog-footer">
                    <el-button @click="deleteDialogShow=false;deleteRow = {}">取 消</el-button>
                    <el-button type="primary" @click="deleteUser">确 定</el-button>
                </span>
        </el-dialog>
    </div>
</template>
<script>
    import AutoSelectForm from '@/components/common/AutoSelectForm'
    import service from '@/api/service'
    import CreateDialogForm from '@/components/common/CreateDialogForm'
    import UpdateDialogForm from '@/components/common/UpdateDialogForm'
    import UserDetail from './container/user/UserDetail'
    import {mapState} from 'vuex'

    export default {
        name: 'User',
        data() {
            return {
                formSearch: {
                    realName: '',
                    deptId: this.$route.query.deptId,
                    roleId: '',
                    forbidden: '',
                    pageNum: 1,
                    pageSize: 10
                },
                total: 0,
                pages: 0,
                tableList: [],
                error: false,
                createDialogFormVisible: false,
                addUserLoading: false,
                updateDialogFormVisible: false,
                updateUserLoading: false,
                updateItem: {},
                form: {
                    userName: "",
                    password: "",
                    realName: "",
                    sex: "",
                    phone: "",
                    deptId: "",
                    roleIds: [],
                    remark: ""
                },
                columns: [
                    {
                        label: '用户名',
                        fieldName: 'userName',
                        type: "input",
                        rules: [
                            {required: true, message: '请填写用户名', trigger: 'blur'}
                        ]
                    },
                    {
                        label: '密码',
                        fieldName: 'password',
                        type: "input",
                        rules: [
                            {required: true, message: '请填写密码', trigger: 'blur'}
                        ]
                    },
                    {
                        label: '姓名',
                        fieldName: 'realName',
                        type: "input",
                        rules: [
                            {required: true, message: '请填写姓名', trigger: 'blur'}
                        ]
                    },
                    {
                        label: '性别',
                        fieldName: 'sex',
                        type: "radio",
                        options: [
                            {value: '1', label: '男'},
                            {value: '2', label: '女'}
                        ],
                        rules: []
                    },
                    {
                        label: '手机号',
                        fieldName: 'phone',
                        type: "input",
                        rules: []
                    },
                    {
                        label: '邮箱',
                        fieldName: 'email',
                        type: "input",
                        rules: []
                    },
                    {
                        label: '组织',
                        fieldName: 'deptId',
                        type: "autoSelect",
                        dataType: "dept",
                        rules: [
                            {required: true, message: '请选择组织', trigger: 'blur'}
                        ]
                    },
                    {
                        label: '角色',
                        fieldName: 'roleIds',
                        type: "autoSelect",
                        dataType: "role",
                        multiple: true,
                        rules: [
                            {required: true, message: '请选择角色', trigger: 'blur'}
                        ]
                    },
                    {
                        label: '文字描述',
                        fieldName: 'remark',
                        type: "textarea",
                        rules: []
                    }
                ],
                userDetailShow: false,
                detailData: {},
                searchLoading: false,
                deleteDialogShow: false,
                deleteRow: {}
            }
        },
        computed: {
            ...mapState({
                autoSelectData: state => state.common.autoSelectData
            })
        },
        methods: {
            async onSubmit() {
                this.formSearch.pageNum = 1;
                let formData = {
                    realName: this.formSearch.realName,
                    deptId: this.formSearch.deptId,
                    roleId: this.formSearch.roleId,
                    forbidden: this.formSearch.forbidden,
                    pageNum: 1,
                    pageSize: this.formSearch.pageSize
                };
                this.searchLoading = true;
                const res = await service.searchUsers(formData);
                this.searchLoading = false;
                if (res.status < 400) {
                    this.formSearch.pageNum = res.res.pageNum;
                    this.formSearch.pageSize = res.res.pageSize;
                    this.total = res.res.total;
                    this.pages = res.res.pages;
                    this.tableList = res.res.result || [];
                }
            },
            selectCb(data) {
                this.formSearch[data.fieldName] = data.value
            },
            //分页
            handleCurrentChange(pageNum) {
                this.formSearch.pageNum = pageNum;
                this.searchCommon();
            },
            async searchCommon() {
                let formData = {
                    realName: this.formSearch.realName,
                    deptId: this.formSearch.deptId,
                    roleId: this.formSearch.roleId,
                    forbidden: this.formSearch.forbidden,
                    pageNum: this.formSearch.pageNum,
                    pageSize: this.formSearch.pageSize,
                };
                this.searchLoading = true;
                const res = await service.searchUsers(formData);
                this.searchLoading = false;
                if (res.status < 400) {
                    this.formSearch.pageNum = res.res.pageNum;
                    this.formSearch.pageSize = res.res.pageSize;
                    this.total = res.res.total;
                    this.pages = res.res.pages;
                    this.tableList = res.res.result || [];
                }
            },
            //新增
            showCreateDialogForm() {
                this.createDialogFormVisible = true;
            },
            hideCreateDialogForm() {
                this.createDialogFormVisible = false;
                this.error = false;
            },
            async addUser(data) {
                this.autoSelectData['dept'].map(item => {
                    if (item.value === data.deptId) {
                        data.deptName = item.label
                    }
                });
                this.addUserLoading = true;
                const res = await service.addUser(data);
                this.addUserLoading = false;
                if (res.status < 400) {
                    this.createDialogFormVisible = false;
                    this.error = false;
                } else {
                    this.error = true;
                }
            },
            //修改
            showUpdateDialogForm(row) {
                this.updateDialogFormVisible = true;
                this.$nextTick(function () {
                    this.updateItem = {
                        ...row,
                        sex: String(row.sex),
                        roleIds: row.roleIds.length === 0 ? [] : String(row.roleIds).split(',')
                    };
                    this.form = Object.assign({}, this.form, {
                        userName: row.userName,
                        password: row.password,
                        realName: row.realName,
                        sex: String(row.sex),
                        phone: row.phone,
                        deptId: row.deptId,
                        roleIds: row.roleIds.length === 0 ? [] : String(row.roleIds).split(','),
                        remark: row.remark
                    });
                })
            },
            hideUpdateDialogForm() {
                this.updateDialogFormVisible = false;
                this.error = false;
                this.updateItem = {};
                this.form = {
                    userName: "",
                    password: "",
                    realName: "",
                    sex: "",
                    phone: "",
                    deptId: "",
                    roleIds: [],
                    remark: ""
                };
            },
            async updateUser(data) {
                this.autoSelectData['dept'].map(item => {
                    if (item.value === data.deptId) {
                        data.deptName = item.label;
                    }
                });
                this.updateUserLoading = true;
                const res = await service.updateUser(data);
                this.updateUserLoading = false;
                if (res.status < 400) {
                    this.tableList = this.tableList.map(item => {
                        if (item.id === data.id) {
                            return Object.assign({}, item, data);
                        }
                        return item;
                    });
                    this.updateDialogFormVisible = false;
                    this.error = false;
                } else {
                    this.error = true;
                }
            },
            //是否启用
            async changeEnable(row) {
                const res = await service.changeUserStatus({
                    id: row.id
                });
                if (res.status < 400) {
                    this.$notify({
                        title: '提示',
                        message: '操作成功',
                        duration: 3000
                    });
                } else {
                    this.tableList = this.tableList.map(item => {
                        if (item.id === row.id) {
                            return Object.assign({}, item, {
                                forbidden: !row.forbidden
                            })
                        }
                        return item;
                    });
                    this.$notify({
                        title: '提示',
                        message: '操作失败',
                        duration: 3000
                    });
                }
            },
            //查看详情
            showUserDetail(row) {
                this.userDetailShow = true;
                this.detailData = row;
            },
            hideUserDetail() {
                this.userDetailShow = false;
                this.detailData = {};
            },
            //删除
            showDeleteDialogForm(row) {
                this.deleteRow = row;
                this.deleteDialogShow = true;
            },
            async deleteUser() {
                const res = await service.deleteUser({
                    id: this.deleteRow.id
                });
                if (res.status < 400) {
                    this.tableList = this.tableList.filter(item => {
                        return item.id !== this.deleteRow.id;
                    });
                    this.deleteDialogShow = false;
                    this.deleteRow = {};
                    this.$notify({
                        title: '提示',
                        message: '删除成功',
                        duration: 3000
                    });
                } else {
                    this.$notify({
                        title: '提示',
                        message: '删除失败',
                        duration: 3000
                    });
                }
            }
        },
        created() {
            this.searchCommon()
        },
        watch: {
            '$route.query.deptId': async function (n) {
                if (n) {
                    this.formSearch.pageNum = 1;
                    let formData = {
                        realName: this.formSearch.realName,
                        deptId: n,
                        roleId: this.formSearch.roleId,
                        forbidden: this.formSearch.forbidden,
                        pageNum: 1,
                        pageSize: this.formSearch.pageSize
                    };
                    this.searchLoading = true;
                    const res = await service.searchUsers(formData);
                    this.searchLoading = false;
                    if (res.status < 400) {
                        this.formSearch.pageNum = res.res.pageNum;
                        this.formSearch.pageSize = res.res.pageSize;
                        this.total = res.res.total;
                        this.pages = res.res.pages;
                        this.tableList = res.res.result || [];
                    }
                }
            }
        },
        components: {
            AutoSelectForm,
            CreateDialogForm,
            UpdateDialogForm,
            UserDetail
        }
    }
</script>
<style scoped lang="stylus">
</style>
